package com.leyou.item.web;

import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.entity.Category;
import com.leyou.item.service.CategoryService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("category")
public class CategoryController {

    private final CategoryService categoryService;

    public CategoryController(CategoryService categoryService) {
        this.categoryService = categoryService;
    }

    /**
     * 根据分类id，查询商品分类
     * @param id    分类id
     * @return      查询到的category转换为categoryDto,
     */
    @GetMapping("/{id}")
    public ResponseEntity<CategoryDTO> queryCategoryById(@PathVariable("id") Long id) {
        Category category = categoryService.getById(id);
        CategoryDTO categoryDTO = new CategoryDTO(category);
        return ResponseEntity.ok(categoryDTO);
    }

    /**
     * 根据分类id的集合，查询商品分类的集合
     * @param ids     分类id的集合
     * @return          商品分类的集合
     */
    @GetMapping("/list")
    public ResponseEntity<List<CategoryDTO>> queryCategoryByIds(@RequestParam("ids")List<Long> ids) {
        List<Category> categoryList = categoryService.listByIds(ids);
//        List<CategoryDTO> categoryDTOS = new ArrayList<>(categoryList.size());
//        for (Category category : categoryList) {
//            categoryDTOS.add(new CategoryDTO(category));
//        }
        //List<CategoryDTO> categoryDTOS = categoryList.stream().map(category -> new CategoryDTO(category)).collect(Collectors.toList());
        List<CategoryDTO> categoryDTOS = CategoryDTO.convertEntityList(categoryList);
        return ResponseEntity.ok(categoryDTOS);
    }

    /**
     * 根据父类目id，查询子类目的集合
     * @param pid   父类目id
     * @return      类目的集合
     */
    @GetMapping("/of/parent")
    public ResponseEntity<List<CategoryDTO>> queryCategoryByPid(@RequestParam("pid")Long pid) {
        //查询
        List<Category> categoryList = categoryService.query().eq("parent_id", pid).list();
        //转换
        List<CategoryDTO> categoryDTOS = CategoryDTO.convertEntityList(categoryList);
        //返回
        return ResponseEntity.ok(categoryDTOS);
    }

    /**
     * 根据品牌id，查询商品分类的集合
     * @param id        品牌id
     * @return          商品分类的集合
     */
    @GetMapping("/of/brand")
    public ResponseEntity<List<CategoryDTO>> queryCategoryByBrandId(@RequestParam("id")Long id) {
        //查询
        List<CategoryDTO> list = categoryService.queryCategoryByBrandId(id);
        //返回
        return ResponseEntity.ok(list);
    }
}
